// 模态框管理模块

// 打开图标编辑/添加模态框
export function openIconModal(iconData = null, index = null, sourceTab = null) {
    const modal = document.getElementById('modal');
    const form = document.getElementById('icon-form');
    const modalTitle = document.getElementById('modal-title');
    const deleteBtn = document.getElementById('modal-delete');
    
    if (!modal || !form || !modalTitle || !deleteBtn) return;
    
    // 重置表单
    form.reset();
    

    
    // 重置封面选择
    document.querySelectorAll('#emoji-picker .emoji-option').forEach(opt => {
        opt.classList.remove('bg-blue-100');
    });
    
    // 重置图片上传
    document.getElementById('image-preview').classList.add('hidden');
    document.getElementById('preview-img').src = '';
    document.getElementById('custom-image').value = '';
    
    // 切换回表情选择
    document.querySelector('input[name="icon-type"][value="emoji"]').checked = true;
    showIconOptions('emoji');
    
    // 设置为编辑或新增模式
    if (iconData) {

        modalTitle.textContent = '编辑导航';

        window.editingIcon = { index, tab: sourceTab || window.currentTab };
        
        // 填充表单
        const nameInput = form.querySelector('[name="name"]');
        nameInput.value = iconData.name || '';
        form.querySelector('[name="url"]').value = iconData.url || '';
        form.querySelector('[name="description"]').value = iconData.description || '';
        
        // 处理不同类型的图标
        if (iconData.customImage) {


            document.querySelector('input[name="icon-type"][value="image"]').checked = true;
            showIconOptions('image');
            toggleImageUpload(true);
            
            document.getElementById('custom-image').value = iconData.customImage;
            document.getElementById('preview-img').src = iconData.customImage;
            document.getElementById('image-preview').classList.remove('hidden');
        } else {

            const cover = iconData.cover;
            if (cover) {

                const emojiOptions = document.querySelectorAll('#emoji-picker .emoji-option');
                emojiOptions.forEach(option => {
                    option.classList.toggle('bg-blue-100', option.textContent === cover);
                });
                document.getElementById('selected-cover').value = cover;
            }
        }
        
        // 显示删除按钮
        deleteBtn.classList.remove('hidden');
    } else {
        modalTitle.textContent = '新增导航';
        window.editingIcon = null;
        
        // 隐藏删除按钮
        deleteBtn.classList.add('hidden');
    }
    
    // 显示弹窗
    modal.classList.remove('hidden');
    
    // 应用通用解决方案 - 防止事件冒泡，确保所有输入控件可点击
    setupModalEventHandlers(modal);
    
    // 聚焦到名称输入框
    setTimeout(() => {
        const nameInput = form.querySelector('[name="name"]');
        if (nameInput) {
            nameInput.focus();
        }
    }, 50);
}

// 关闭模态框
export function closeIconModal() {
    const modal = document.getElementById('modal');
    if (modal) {
        modal.classList.add('hidden');
    }
    window.editingIcon = null;
}

// 显示不同的图标选项
export function showIconOptions(type) {
    console.log('切换图标类型:', type);
    const emojiPicker = document.getElementById('emoji-picker');
    const imageUpload = document.getElementById('image-upload');
    
    if (emojiPicker) {
        emojiPicker.classList.toggle('hidden', type !== 'emoji');
    } else {
        console.error('未找到emoji-picker元素');
    }
    
    if (imageUpload) {
        imageUpload.classList.toggle('hidden', type !== 'image');
    } else {
        console.error('未找到image-upload元素');
    }
    
    // 确保点击事件在表情选项上正常工作
    if (type === 'emoji') {
        setTimeout(() => {
            const emojiOptions = document.querySelectorAll('#emoji-picker .emoji-option');
            emojiOptions.forEach(option => {
                option.onclick = function(e) {
                    e.stopPropagation();

                    emojiOptions.forEach(opt => opt.classList.remove('bg-blue-100'));

                    this.classList.add('bg-blue-100');
                    document.getElementById('selected-cover').value = this.textContent;

                };
            });
        }, 0);
    }
}

// 强制显示/隐藏图片上传区域
export function toggleImageUpload(show) {

    const imageUpload = document.getElementById('image-upload');
    if (imageUpload) {
        if (show) {
            imageUpload.classList.remove('hidden');

        } else {
            imageUpload.classList.add('hidden');

        }
    } else {
        console.error('未找到image-upload元素');
    }
}

// 模态框事件处理
export function setupModalEventHandlers(modalElement) {
    if (!modalElement) return;
    
    // 先移除可能存在的旧事件监听器，避免重复绑定
    modalElement.onclick = null;
    
    // 设置模态框点击事件 - 仅关闭背景点击
    modalElement.onclick = function(e) {
        // 只有点击模态框背景时才关闭，确保不干扰输入框交互
        if (e.target === modalElement) {
            closeIconModal();
        }
        // 不阻止事件冒泡，让输入框正常处理点击事件
    };
    
    // 确保所有输入框可以正常获得焦点
    const inputs = modalElement.querySelectorAll('input, textarea');
    inputs.forEach(input => {

        input.style.pointerEvents = 'auto';
        input.style.userSelect = 'auto';
        

        input.addEventListener('mousedown', function(e) {
            e.stopPropagation();
        });
        
        input.addEventListener('click', function(e) {
            e.stopPropagation();
            this.focus();
        });
    });
}

// 导出模块
export default {
    openIconModal,
    closeIconModal,
    showIconOptions,
    toggleImageUpload,
    setupModalEventHandlers
};